import { supabase } from "@/supabase/supabaseClient";

export default {
  namspaced: true,
  state() {
    return {
      lastFetch: null, // timestamp
      error: null,
      coaches: [
        {
          id: "c1",
          firstName: "Max",
          lastName: "flycool",
          areas: ["frontend", "backend", "career", "android"],
          description: "I'm Max and I've worked as a freedom developer",
          hourlyRate: 30,
        },
        {
          id: "c2",
          firstName: "ting",
          lastName: "ting",
          areas: ["frontend", "career"],
          description: "I'm ting ting",
          hourlyRate: 30,
        },
      ],
    };
  },
  mutations: {
    registerCoach(state, payload) {
      state.coaches.push(payload);
    },
    setCoaches(state, payload) {
      state.coaches = payload;
    },
    setFetchTimestamp(state) {
      state.lastFetch = new Date().getTime();
    },
  },
  actions: {
    async registerCoach(context, data) {
      const userId = context.getters.userId;
      const coachData = {
        firstName: data.firstName,
        lastName: data.lastName,
        description: data.description,
        hourlyRate: data.hourlyRate,
        areas: data.areas,
      };

      const token = context.getters.token;
      console.log(userId);
      console.log(token);

      const { responseData, error } = await supabase
        .from("coach")
        .insert(coachData);

      if (error) {
        return;
      }

      context.commit("registerCoach", {
        ...coachData,
        id: userId,
      });
    },
    async loadCoaches(context, payload) {
      if (!payload.foreceRefresh && !context.getters.shouldUpdate) {
        return;
      }

      const { data, error } = await supabase.from("coach").select();
      //console.log('loadcoaches:', data);

      if (error) {
        context.state.error = error.message;
      }

      context.commit("setCoaches", data);
      context.commit("setFetchTimestamp");
    },
  },
  getters: {
    coaches(state) {
      return state.coaches;
    },
    hasCoaches(state) {
      return state.coaches && state.coaches.length > 0;
    },
    isCoach(_, getters, _2, rootGetters) {
      const coaches = getters.coaches;
      const userId = rootGetters.userId;
      return coaches.some((coach) => coach.id === userId);
    },
    hasError(state) {
      return state.error !== null;
    },
    getError(state) {
      return state.error;
    },
    shouldUpdate(state) {
      const lastFetch = state.lastFetch;
      if (!lastFetch) {
        return true;
      }
      const currentTimestamp = new Date().getTime();
      return (currentTimestamp - lastFetch) / 1000 > 60; // > 1 min
    },
  },
};
